package com.lincoln.framework.controller.api;

import com.lincoln.framework.common.Constant;
import com.lincoln.framework.common.ApiCode;
import com.lincoln.framework.common.WebUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Iterator;

/**
 * 
 * 通用上传
 * 
 * @author Administrator
 * 
 */
@Controller
@RequestMapping("/api/upload")
public class UploadApiController extends BaseApiController {

	/**
	 * 上传图片
	 * 
	 * @param request
	 */
	@ResponseBody
	@RequestMapping("/uploadImage.do")
	public void uploadImage(MultipartHttpServletRequest request) {
		Iterator<String> itr = request.getFileNames();
		MultipartFile mpf;
		String fileName = System.currentTimeMillis() + ".jpg";
		String imagePath = Constant.TEMP_DIR + "/" + fileName;
		File avatarFile = new File(WebUtils.getContextPath() + imagePath);
		while (itr.hasNext()) {
			// 验证文件类型
			try {
				BufferedImage imageBuff = null;
				mpf = request.getFile(itr.next());
				imageBuff = ImageIO.read(mpf.getInputStream());
				if (imageBuff == null) {
					this.returnError(ApiCode.PARAMETER_WRONG);
					return;
				}
				if (!avatarFile.exists()) {
					avatarFile.createNewFile();
				}
				mpf.transferTo(avatarFile);
			} catch (Exception e) {
				this.returnError(ApiCode.PARAMETER_WRONG);
				return;
			}
		}
		this.setAttributes("imageUrl", imagePath);
		this.returnSuccess();
	}
}
